﻿using CleanArchitecture.Infrastructure.Models.Business.Columns;
using CleanArchitecture.Web.Factories;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CleanArchitecture.Web.Controllers.Frontend
{
    public class BaseFrontendController : BaseController
    {
        #region Field
        private readonly IBusinessModelFactory _businessmodelFactory;
        #endregion

        #region Ctor
        public BaseFrontendController(IBusinessModelFactory businessModelFactory)
        {
            _businessmodelFactory = businessModelFactory;
        }
        #endregion
        /// <summary>
        /// 通用方法，递归查找当前菜单栏的父级菜单,直至找到根栏目(即一级菜单)
        /// </summary>
        /// <param name="column"></param>
        /// <param name="allColumns"></param>
        protected void GetRootColumn(ColumnItemModel column, IList<ColumnItemModel> allColumns)
        {
            Func<ColumnItemModel, ColumnItemModel> FindRootColumn = null;
            FindRootColumn = column =>
            {
                if (column == null) return null;
                else if (column.Level == 1) return column;
                var parent = allColumns.FirstOrDefault(c => c.Id == column.ParentId);
                return FindRootColumn(parent);
            };
            ViewBag.RootColumn = FindRootColumn(column);
        }
        /// <summary>
        /// 通用方法 获取当前菜单栏的面包屑
        /// 顺序为从根栏目至当前查找的栏目
        /// </summary>
        /// <param name="column"></param>
        protected void GetBreadColumns(ColumnItemModel column)
        {
            if (column == null) return;
            var breadCrumbs = _businessmodelFactory.GetColumnBreadcrumb(column.Id);
            if (breadCrumbs.Count > 0)
                ViewBag.BreadColumns = breadCrumbs.Reverse().ToList();
        }
    }
}
